<?php
namespace app\api\controller;

use think\exception\ValidateException;
use think\Response;
use think\facade\Db;
use think\Image;

class UpLoad extends Base
{
    // 上传表单页面
    public function index(): Response
    {
        $maxWidth = config('app.max_width');
        $maxHeight = config('app.max_height');

        $file = request()->file('image');
        if($file){

            // 文件的本地存储路径
            //$path = ROOT_PATH . 'public' . DS . 'upload';
            // 校验并移动
            try {
                // 校验数组
                //$validateArr = ['image'=>' fileExt:jpg,jpeg,gif,png,bmp' ];
                //验证器验证上传的文件
                //validate($validateArr)->check(['file'=>$file]);
                validate(['file'=>'fileExt:jpg,jpeg,gif,png,bmp'])
                    ->check(['file'=>$file]);
            }catch (ValidateException $e) {
                $msg = $e->getMessage();
                return $this->create(['url' => ''] , $msg, 202);
            }
            $info = $filename = \think\facade\Filesystem::disk('public')->putFile('uploads',$file);
            //$info = $file->move($path);
            // 检查移动结果
            if($info){
                // 上传成功
                $imagefile = root_path() .'public/' . $filename;
                $imagefile = str_replace("\\","/",$imagefile);
                $image = Image::open($imagefile);
                //dd($image);
                $image->thumb($maxWidth, $maxHeight)->save($imagefile);

                $filename = str_replace("\\","/",$filename);
                $filesize = filesize($imagefile);
                $image = Image::open($imagefile);
                //存入上传文件管理数据表
                $data = [
                    'upload_type'   => 'local',
                    'original_name' => 'API',
                    'mime_type'     => $image->mime(),
                    'image_width'  => $image->width(),
                    'image_height'  => $image->height(),
                    'image_type'   => $image->type(),
                    'file_size'     => $filesize,
                    'file_ext'      => strtolower($file->getOriginalExtension()),
                    'url'           => '/' . $filename,
                    'create_time'   => time(),
                ];
                DB::name('SystemUploadfile')->save($data);
                $url = $filename;
                $code   =  '200';
                $msg    =  '图片上传成功';
                $data    =  [ 'url' => $url] ;
            }else{
                // 上传失败，返回json，告知客户端
                $code   =  '202';
                $msg    =  '图片上传失败';
                $data    =  [ 'url' => ''] ;
            }
        }else{
            // 未上传文件
            $code   =  '404';
            $msg    =  '未选择图片';
            $data    =  [ 'url' => ''] ;
        }
        return $this->create($data, $msg, $code);
    }
}


